<template>
	<div
		class="date-range-picker"
		ref="calendarContainer">
		<!-- <div class="calendar-wrapper"> -->
		<div class="header">
			<li id="prevMonth"></li>
			<li class="year-month">
				<span class="choose-month">{{ year_data }}</span>
			</li>
			<li id="nextMonth"></li>
		</div>
		<div class="table_box">
			<table>
				<tbody>
					<tr v-for="item in Date_timelist">
						<td
							v-for="i in item"
							:class="{
								'other-month':
									i.getMonth() != currentMonth_value,
								dade_adtive:
									i.getDate() == new Date().getDate() &&
									i.getMonth() == new Date().getMonth() &&
									i.getFullYear() == new Date().getFullYear()
							}"
							:data-date="i.toISOString()"
							@click="item_acitve(i)">
							{{ i.getDate() }}
						</td>
					</tr>
				</tbody>
			</table>
		</div>
		<!-- </div> -->
	</div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';

let props = defineProps({
	modelValue: {
		type: Object,
		default: null
	}
});
const emit = defineEmits(['change_time']);
let Date_timelist = ref([]);
let currentMonth_value = ref(new Date().getMonth());
const calendarContainer = ref(null);
let startDate = ref(null);
let endDate = ref(null);
let year_data = ref('');
if (props.modelValue) {
	if (props.modelValue.start)
		startDate.value = new Date(props.modelValue.start);
	if (props.modelValue.end) endDate.value = new Date(props.modelValue.end);
}

onMounted(() => {
	initPicker();
	renderCalendar();
	updateHighlight();
});

// 封装的日期范围选择逻辑
class DateRangePicker {
	constructor(container, onChange) {
		this.container = container;
		this.onChange = onChange;
		this.currentYear = new Date().getFullYear();
		this.currentMonth = new Date().getMonth();
		this.renderCalendar();
	}

	generateCalendar(year, month) {
		const firstDay = new Date(year, month, 1);
		const weeks = [];
		let currentWeek = [];
		const startDay = firstDay.getDay() == 0 ? 7 : firstDay.getDay();
		// 计算上月的最后几天
		for (let i = startDay - 1; i >= 0; i--) {
			const date = new Date(year, month, 1 - i);
			currentWeek.push(date);
		}
		for (let date = 1; date <= 42 - startDay; date++) {
			const currentDate = new Date(year, month, date + 1);
			if (currentWeek.length == 7) {
				weeks.push(currentWeek);
				currentWeek = [];
			}
			currentWeek.push(currentDate);
		}
		if (currentWeek.length > 0) {
			const remaining = 7 - currentWeek.length;
			for (let i = 0; i < remaining; i++) {
				const date = new Date(year, month + 1, i + 1);
				currentWeek.push(date);
			}
			weeks.push(currentWeek);
		}
		return weeks;
	}

	renderCalendar() {
		// 头部
		year_data.value = `${this.currentYear} - ${
			this.currentMonth + 1 >= 10
				? this.currentMonth + 1
				: '0' + (this.currentMonth + 1)
		}`;
		// 日历表
		const weeks = this.generateCalendar(
			this.currentYear,
			this.currentMonth
		);
		Date_timelist.value = weeks;
		currentMonth_value.value = this.currentMonth;
		// // const thead = document.createElement('thead');
		// // const headerRow = document.createElement('tr');
		// // ['日', '一', '二', '三', '四', '五', '六'].forEach(d => {
		// // 	const th = document.createElement('th');
		// // 	th.innerText = d;
		// // 	headerRow.appendChild(th);
		// // });
		// // thead.appendChild(headerRow);
		// // table.appendChild(thead);
		// console.log(weeks);

		// 按钮事件
		if (
			document.querySelector('#prevMonth') &&
			document.querySelector('#nextMonth')
		) {
			document.querySelector('#prevMonth').onclick = () => {
				this.currentMonth--;
				if (this.currentMonth < 0) {
					this.currentMonth = 11;
					this.currentYear--;
				}
				this.renderCalendar();
				this.updateHighlight();
			};
			document.querySelector('#nextMonth').onclick = () => {
				this.currentMonth++;
				if (this.currentMonth > 11) {
					this.currentMonth = 0;
					this.currentYear++;
				}
				this.renderCalendar();
				this.updateHighlight();
			};
		}
	}

	onDateClick(date) {
		if (!date) return;
		if (!startDate.value || (startDate.value && endDate.value)) {
			startDate.value = date;
			endDate.value = null;
		} else if (startDate.value && !endDate.value) {
			if (date >= startDate.value) {
				endDate.value = date;
			} else {
				endDate.value = startDate.value;
				startDate.value = date;
			}
		}
		this.updateHighlight();
		this.onChange(this.getRange());
	}

	updateHighlight() {
		const tds = this.container.querySelectorAll('td[data-date]');
		setTimeout(() => {
			tds.forEach(td => {
				const dateStr = td.dataset.date;
				if (!dateStr) return;
				const date = new Date(dateStr);
				td.classList.remove('selected', 'in-range');
				if (
					startDate.value &&
					!endDate.value &&
					date.toDateString() === startDate.value.toDateString()
				) {
					td.classList.add('selected');
				} else if (
					startDate.value &&
					endDate.value &&
					date >= startDate.value &&
					date <= endDate.value
				) {
					if (
						date.toDateString() ===
							startDate.value.toDateString() ||
						date.toDateString() === endDate.value.toDateString()
					) {
						td.classList.add('selected');
					} else {
						td.classList.add('in-range');
					}
				}
			});
		}, 5);
	}

	getRange() {
		return {
			start: this.formatDate(startDate.value),
			end: this.formatDate(endDate.value)
		};
	}

	formatDate(date) {
		if (!date) return null;
		const y = date.getFullYear();
		const m = ('0' + (date.getMonth() + 1)).slice(-2);
		const d = ('0' + date.getDate()).slice(-2);
		const h = ('0' + date.getHours()).slice(-2);
		const min = ('0' + date.getMinutes()).slice(-2);
		const s = ('0' + date.getSeconds()).slice(-2); // 秒
		return `${y}-${m}-${d} ${h}:${min}:${s}`;
	}
}

// 组件内部逻辑
let pickerInstance = null;

const initPicker = () => {
	if (pickerInstance) return;
	pickerInstance = new DateRangePicker(calendarContainer.value, range => {
		if (range) {
			emit('change_time', range);
		} else {
			emit('change_time', null);
		}
	});
};

const renderCalendar = () => {
	if (pickerInstance) {
		pickerInstance.currentYear = pickerInstance.currentYear; // force re-render
		pickerInstance.renderCalendar();
		pickerInstance.updateHighlight();
	}
};

const updateHighlight = () => {
	if (pickerInstance) {
		pickerInstance.updateHighlight();
	}
};

const item_acitve = item => {
	pickerInstance.onDateClick(item);
};
onMounted(() => {
	initPicker();
});
</script>

<style scoped>
* {
	box-sizing: border-box;
	list-style: none;
}
.date-range-picker {
	width: 100%;
	height: 100%;
}
.header {
	display: flex;
	align-items: center;
}
.header {
	display: flex;
	justify-content: space-around;
}

#prevMonth {
	width: 15px;
	height: 15px;
	text-align: center;
	background-image: url('../../../assets/sb/xin/ICON-LIFT-DJ.svg');
	background-size: cover;
	background-size: 100% 100%;
	cursor: pointer;
	margin: auto 0;
}

#nextMonth {
	width: 15px;
	height: 15px;
	text-align: center;
	background-image: url('../../../assets/sb/xin/ICON-RIGHT-DJ.svg');
	background-size: cover;
	background-size: 100% 100%;
	/* transform: rotatez(180deg); */
	cursor: pointer;
	margin: auto 0;
}

.choose-month {
	display: block;
	width: 100px;
	text-align: center;
	color: #fff;
	font-size: 12px;
	line-height: 18px;
}

.table_box {
	width: 100%;
	margin: 0 auto;
	display: flex;
	flex-wrap: wrap;
	justify-content: space-around;
	padding: 0px 3px 0 3px;
}
table,
tbody {
	width: 100%;
	display: inline-block;
}
tr {
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: space-between;
}
td {
	width: 13%;
	display: inline-block;
	height: 15px;
	text-align: center;
	cursor: pointer;
	color: #fff;
	border-radius: 20%;
	font-size: 10px;
}
td:hover {
	color: #789af7;
}
.other-month {
	color: #999;
}
.dade_adtive {
	background: rgba(100, 161, 211, 0.8);
}
td.selected {
	background-color: #3399ff;
	color: #fff;
}
td.in-range {
	background-color: #cce5ff;
}
</style>
